package com.scap.dfs.dao.impl;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.persister.entity.AbstractEntityPersister;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.scap.dfs.dao.DailyCalFormulaDao;
import com.scap.dfs.model.DailyCalFormula;
import com.scap.dfs.model.DailyCalFormulaConfig;
import com.scap.dfs.model.DailyCalFormulaPK;

@Repository
public class DailyCalFormulaDaoImpl implements DailyCalFormulaDao {
	
	final static Logger logger = Logger.getLogger(DailyCalFormulaDaoImpl.class);
	
	@Autowired
	SessionFactory sessionFactory;

	@Override
	public boolean insert(DailyCalFormula dailyCalFormula) {
		DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
		Date date = new Date();
		dailyCalFormula.setUpdateTime(dateFormat.format(date));
		dateFormat = new SimpleDateFormat("yyyyMMdd");
		dailyCalFormula.setUpdateDate(dateFormat.format(date));
		
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		try{
			Serializable result = null;
			result = session.save(dailyCalFormula);
			System.out.println("Result form add DailyCalFormula : "+result);
			tx.commit();
		}
		catch(Exception e){
			logger.error(e);
			tx.rollback();
			return false;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return true;
	}

	@Override
	public boolean update(DailyCalFormula d1) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		
		try{
			
			DailyCalFormula d2 = (DailyCalFormula) session.get(DailyCalFormula.class, d1.getId());
			d2.setActivation(d1.getActivation()!=null?d1.getActivation():d2.getActivation());
			d2.setFlowNumber(d1.getFlowNumber()!=null?d1.getFlowNumber():d2.getFlowNumber());
			d2.setFormulaName(d1.getFormulaName()!=null?d1.getFormulaName():d2.getFormulaName());
			d2.setId(d1.getId()!=null?d1.getId():d2.getId());
			d2.setVar1ColumnName(d1.getVar1ColumnName()!=null?d1.getVar1ColumnName():d2.getVar1ColumnName());
			d2.setVar2ColumnName(d1.getVar2ColumnName()!=null?d1.getVar2ColumnName():d2.getVar2ColumnName());
			d2.setVar3ColumnName(d1.getVar3ColumnName()!=null?d1.getVar3ColumnName():d2.getVar3ColumnName());
			
			DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
			Date date = new Date();
			d2.setUpdateTime(dateFormat.format(date));
			dateFormat = new SimpleDateFormat("yyyyMMdd");
			d2.setUpdateDate(dateFormat.format(date));
			session.update(d2);
			
			tx.commit();
		}
		catch(Exception e){
			logger.error(e);
			tx.rollback();
			return false;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return true;
	}

	@Override
	public boolean delete(DailyCalFormulaPK pk) {
		DailyCalFormula d = new DailyCalFormula();
		d.setId(pk);
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		try{
			session.delete(d);
			tx.commit();
		}
		catch(Exception e){
			logger.error(e);
			tx.rollback();
			return false;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return true;
	}

	@Override
	public DailyCalFormula findById(DailyCalFormulaPK pk) {
		Session session = sessionFactory.openSession();
		DailyCalFormula d = null;
		try{
			d = (DailyCalFormula) session.get(DailyCalFormula.class,pk);
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return d;
	}

	@Override
	public List getListByHospitalCodeOrderByFlowNumber(String hospitalCode) {
		Session session = sessionFactory.openSession();
		List<DailyCalFormula> dailyCalFormulas = null;
		try{
			Criteria cr = session.createCriteria(DailyCalFormula.class);
			cr.add(Restrictions.like("id.hospitalCode",hospitalCode));
			cr.add(Restrictions.eq("activation",true));
			cr.addOrder(Order.asc("flowNumber"));
			dailyCalFormulas = cr.list();
			
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return dailyCalFormulas;
	}

	@Override
	public List getListPerPage(int amount, int page, String orderByColumnName,
			String ascOrDesc) {
		Session session = sessionFactory.openSession();
		int firstElement = amount*(page-1);
		List<DailyCalFormula> dailyCalFormulas = null;
		
		try{
			
			Criteria cr = session.createCriteria(DailyCalFormula.class);
			cr.setFirstResult(firstElement);
			cr.setMaxResults(amount);
			if(ascOrDesc=="desc"||ascOrDesc.equals("desc")){
				cr.addOrder(Order.desc(orderByColumnName));
			}
			else{
				cr.addOrder(Order.asc(orderByColumnName));
			}
			dailyCalFormulas = cr.list();
			
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return dailyCalFormulas;
	}

	@Override
	public List findByAttribute(DailyCalFormula dailyCalFormula) {
		
		Session session = sessionFactory.openSession();
		List dailyCalFormulas = null;
		
		Criteria cr = session.createCriteria(DailyCalFormula.class);
		if(dailyCalFormula.getActivation()!=null)cr.add(Restrictions.eq("activation",dailyCalFormula.getActivation()));
		if(dailyCalFormula.getFlowNumber()!=null)cr.add(Restrictions.eq("flowNumber", dailyCalFormula.getFlowNumber()));
		if(dailyCalFormula.getFormulaName()!=null)cr.add(Restrictions.like("formulaName",dailyCalFormula.getFormulaName()));
		if(dailyCalFormula.getUpdateDate()!=null)cr.add(Restrictions.like("updateDate",dailyCalFormula.getUpdateDate()));
		if(dailyCalFormula.getUpdateTime()!=null)cr.add(Restrictions.like("updateTime",dailyCalFormula.getUpdateTime()));
		
		if(dailyCalFormula.getVar1ColumnName()!=null)cr.add(Restrictions.like("var1ColumnName",dailyCalFormula.getVar1ColumnName()));
		if(dailyCalFormula.getVar2ColumnName()!=null)cr.add(Restrictions.like("var2ColumnName",dailyCalFormula.getVar2ColumnName()));
		if(dailyCalFormula.getVar3ColumnName()!=null)cr.add(Restrictions.like("var3ColumnName",dailyCalFormula.getVar3ColumnName()));
		
		if(dailyCalFormula.getId().getFormulaId()!=null)cr.add(Restrictions.eq("id.formulaId",dailyCalFormula.getId().getFormulaId()));
		if(dailyCalFormula.getId().getHospitalCode()!=null)cr.add(Restrictions.like("id.hospitalCode",dailyCalFormula.getId().getHospitalCode()));
		
		cr.addOrder(Order.asc("id.hospitalCode"));
		cr.addOrder(Order.asc("id.formulaId"));
		
		dailyCalFormulas = cr.list();
		
		return dailyCalFormulas;
		
	}

	@Override
	public List findByAttributePerPage(DailyCalFormula dailyCalFormula,
			int amount, int page, String orderByColumnName, String ascOrDesc) {
		Session session = sessionFactory.openSession();
		int firstElement = amount*(page-1);
		List<DailyCalFormula> dailyCalFormulas = null;
		
		try{
			
			Criteria cr = session.createCriteria(DailyCalFormula.class);
			if(dailyCalFormula.getActivation()!=null)cr.add(Restrictions.eq("activation",dailyCalFormula.getActivation()));
			if(dailyCalFormula.getFlowNumber()!=null)cr.add(Restrictions.eq("flowNumber", dailyCalFormula.getFlowNumber()));
			if(dailyCalFormula.getFormulaName()!=null)cr.add(Restrictions.like("formulaName",dailyCalFormula.getFormulaName()));
			if(dailyCalFormula.getUpdateDate()!=null)cr.add(Restrictions.like("updateDate",dailyCalFormula.getUpdateDate()));
			if(dailyCalFormula.getUpdateTime()!=null)cr.add(Restrictions.like("updateTime",dailyCalFormula.getUpdateTime()));
			
			if(dailyCalFormula.getVar1ColumnName()!=null)cr.add(Restrictions.like("var1ColumnName",dailyCalFormula.getVar1ColumnName()));
			if(dailyCalFormula.getVar2ColumnName()!=null)cr.add(Restrictions.like("var2ColumnName",dailyCalFormula.getVar2ColumnName()));
			if(dailyCalFormula.getVar3ColumnName()!=null)cr.add(Restrictions.like("var3ColumnName",dailyCalFormula.getVar3ColumnName()));
			
			if(dailyCalFormula.getId().getFormulaId()!=null)cr.add(Restrictions.eq("id.formulaId",dailyCalFormula.getId().getFormulaId()));
			if(dailyCalFormula.getId().getHospitalCode()!=null)cr.add(Restrictions.like("id.hospitalCode",dailyCalFormula.getId().getHospitalCode()));
			
			
			if(ascOrDesc=="desc"||ascOrDesc.equals("desc")){
				cr.addOrder(Order.desc(orderByColumnName));
			}
			else{
				cr.addOrder(Order.asc(orderByColumnName));
			}
			dailyCalFormulas = cr.list();
			
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		finally{
			session.flush();
			session.clear();
			session.close();
		}
		return dailyCalFormulas;
	}
	
	@Override
	public String getAttributeNameByColumnName(String columnName) {
//		Session session = sessionFactory.openSession();
		
		String attrName;
		
		AbstractEntityPersister aep=((AbstractEntityPersister)sessionFactory.getClassMetadata(DailyCalFormula.class));  
		String[] properties=aep.getPropertyNames();  
		try{
		
			if(columnName == ""||columnName.equals("")){
				for(int nameIndex=0;nameIndex!=properties.length;nameIndex++){  
					   System.out.println("Property name: "+properties[nameIndex]);  
					   String[] columns=aep.getPropertyColumnNames(nameIndex);  
					   for(int columnIndex=0;columnIndex!=columns.length;columnIndex++){  
					      System.out.println("Column name: "+columns[columnIndex]);  
					   }  
					} 
				
			}
		else{	
		for(int nameIndex=0;nameIndex!=properties.length;nameIndex++){  
	//			   System.out.println("Property name: "+properties[nameIndex]);  
				   String[] columns=aep.getPropertyColumnNames(nameIndex);  
				   for(int columnIndex=0;columnIndex!=columns.length;columnIndex++){  
					  if(columns[columnIndex].equals(columnName)||columns[columnIndex]==columnName){
						  return properties[nameIndex];
					  }
	//			      System.out.println("Column name: "+columns[columnIndex]);  
				   }  
				} 
			}
		}
		catch(Exception e){
			logger.error(e);
			return null;
		}
		
		return null;
	}

}
